(function() {
  'use strict';

  angular.module('app')
    .factory('CommonService', ['$http', '$q', '$rootScope', '$state', CommonService]);

  function CommonService($http, $q, $rootScope, $state) {

    var restInterfaceUrls = {};

    var urlPrefix = '/';

    var service = {
      get: get,
      put: put,
      del: del,
      post: post,
      uploadFile: uploadFile,
      getUrlPrefix: getUrlPrefix
    };

    return service;

    //////////////////

    function get(url, params) {
      return $q(function(resovle, reject) {
        $http({
          url: urlPrefix + url,
          method: 'GET',
          params: { 'data': JSON.stringify(params) },
        }).then(function(response, header, config, status) {
          handle(response, resovle, reject);
        }, function(response, header, config, status) {
          reject('接口访问异常');
        });
      });
    }

    function del(url, params) {
      return $q(function(resovle, reject) {
        $http({
          url: urlPrefix + url,
          method: 'DELETE',
          params: { 'data': JSON.stringify(params) },
        }).then(function(response, header, config, status) {
          handle(response, resovle, reject);
        }, function(response, header, config, status) {
          reject('接口访问异常');
        });
      });
    }

    function put(url, data) {
      return $q(function(resovle, reject) {
        $http({
          url: urlPrefix + url,
          method: 'PUT',
          data: data,
        }).then(function(response, header, config, status) {
          handle(response, resovle, reject);
        }, function(response, header, config, status) {
          reject('接口访问异常');
        });
      });
    }

    function post(url, data) {
      return $q(function(resovle, reject) {
        $http({
          url: urlPrefix + url,
          method: 'POST',
          data: data,
        }).then(function(response, header, config, status) {
          handle(response, resovle, reject);
        }, function(response, header, config, status) {
          reject('接口访问异常');
        });
      });
    }

    function uploadFile(url, data) {
      return $q(function(resovle, reject) {
        $http({
          url: urlPrefix + url,
          method: 'POST',
          data: data,
          headers: { 'Content-Type': undefined },
          transformRequest: angular.identity
        }).then(function(response, header, config, status) {
          handle(response, resovle, reject);
        }, function(response, header, config, status) {
          reject('接口访问异常');
        });
      });
    }

    function getUrlPrefix() {
      return urlPrefix;
    }

    function handle(response, resovle, reject) {
      var data = response.data;
      if (data.status === 'SUCCESS') {
        resovle(data.result);
      } else if (data.status === 'ERROR') {
        reject(data.message);
      } else {
        reject(data.message);
      }
    }
  }
})();